package com.lzh.shijicloudstack.utils;

import cn.hutool.core.util.StrUtil;
import org.apache.ibatis.jdbc.SQL;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.persistence.Column;
import javax.persistence.Table;
import java.lang.reflect.Field;

/**
 * @author luzhiheng
 * @date 2025-02-10
 */
@Component
public class SqlUtil {

    @Resource
    private SqlSessionFactory sqlSessionFactory;

    @Resource
    private JdbcUtil jdbcUtil;

    public String getUpdateSql(Object obj) {
        try {
            Class<?> clazz = obj.getClass();
            Field[] fields = clazz.getDeclaredFields();
            SQL sql = new SQL();
            // 表名
            String tableName = clazz.getAnnotation(Table.class).name();
            sql.UPDATE(tableName);
            // 主键ID
            Field idField = clazz.getSuperclass().getDeclaredField("id");
            idField.setAccessible(true);
            Object id = idField.get(obj);
            sql.WHERE("id = " + id);
            // 属性值列表
            for (Field field : fields) {
                field.setAccessible(true);
                String typeName = field.getType().getName();
                Column fieldAnnotation = field.getAnnotation(Column.class);
                // 列名
                String fieldName = fieldAnnotation.name();
                // 字段值
                Object fieldValue = field.get(obj);
                if ("java.lang.String".equalsIgnoreCase(typeName)) {
                    String value = (String) fieldValue;
                    if (StrUtil.isEmpty(value)) {
                        sql.SET(fieldName + " = NULL");
                    } else {
                        sql.SET(fieldName + " = '" + fieldValue + "'");
                    }
                } else {
                    sql.SET(fieldName + " = " + fieldValue);
                }
            }
            return sql.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public int executeUpdateSql(String sql) {
        return jdbcUtil.executeUpdateSql(sql);
    }
}
